package com.apps.ftapp.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;


import androidx.annotation.IdRes;
import androidx.fragment.app.FragmentActivity;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.CusomizeaAdapter;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.duobeiyun.bean.ChatBean;
import com.duobeiyun.callback.OfflinePlaybackMessageCallback;
import com.duobeiyun.util.CommonUtils;
import com.duobeiyun.util.DuobeiYunClient;
import com.duobeiyun.util.Unzip;
import com.duobeiyun.widget.OfflinePlaybackPlayer;
import com.duobeiyun.widget.OfflinePlayerView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import me.leefeng.promptlibrary.PromptDialog;

/**
 * 离线回放
 */
public class CustomizedOffinePlayBackActivity extends FragmentActivity implements View.OnClickListener, OfflinePlaybackMessageCallback {
    private static final String ROOMID = "roomId";
    private Context mContext;
    private OfflinePlaybackPlayer player;

    //竖向导航
    private RelativeLayout portraitNaviLayout;
    private Button portraitBackBtn; //竖向返回按钮
    //横向导航
    private RelativeLayout landscapeNaviLayout;
    private ImageButton landscapeBackBtn;//横向返回按钮
    //private TextView landscapeCourseTitleText;//横向课程名称
    //ppt显示
    private RelativeLayout pptLayout;
    //竖向播放控制
    private RelativeLayout portraitPlaybackControlLayout;
    private ImageButton portraitControlBtn;//竖向播放控制
    private ImageButton portraitFullScreenBtn;//竖向进入全屏
    private SeekBar portraitSeekbar;//竖向进度
    private TextView portraitCurrentTimeText;//竖向当前时间
    private TextView portraitTotalTimeText;//竖向总时间
    private TextView portraitPlaybackSpeedBtn;//竖向回放速度控制
    //横向播放控制
    private RelativeLayout landscapePlaybackControlLayout;
    private ImageButton landscapeControlBtn;//横向播放控制
    private TextView landscapeCurrentTimeText;//横向当前时间
    private ImageButton landscapeFullScreenBtn;//横向退出全屏
    private TextView landscapePlaybackSpeedBtn;//横向回放速度控制
    private TextView landscapeTotalTimeText;//横向总时间
    private SeekBar landscapeSeekbar;//横向进度

    //聊天区域
    private RelativeLayout chatLayout;
    private ListView chatList;
    private ListView teacherList;
    private RadioGroup chatGroup;
    private RadioButton allMsgBtn, teacherMsgBtn;

    private CusomizeaAdapter cusomizeaAdapter;
    private CusomizeaAdapter teacherAdapter;

    //房间相关的
    private String roomId;
    private ProgressBar load;
    private boolean isPlayerStart = true; // 判断是否开始播放
    private boolean isPlaying = true;//判断是否正在播放
    private OfflinePlayerView mPlayerView;
    private String filePath;
    private Handler handler = null;
    private PromptDialog promptDialog;


    private final int DOSHOW = 1;
    private final int DOHIDE = 2;
    private Boolean ifshow = true;

    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customized_offine_play_back);
        this.mContext = this;

        initView();
        otherCallback();
        //创建属于主线程的handler
        handler = new Handler();
        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        roomId = bundle.getString("roomId");
        filePath = bundle.getString("filePath");
        promptDialog = new PromptDialog(CustomizedOffinePlayBackActivity.this);
        //判断
        File file = new File(filePath + roomId);
        if (!file.exists()) {

            promptDialog.showLoading("视频解压中,请勿关闭....");
//
//            ZipUtil.upzipFile(filePath+"/"+roomId+".zip", filePath);
//            promptDialog.dismiss();
//            player.play();//开始播放
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //ZipUtil.upzipFile(filePath + "/" + roomId + ".zip", filePath);
                    try {
                        L.i("param1", filePath + roomId);
                        Unzip.unzip(new File(filePath + roomId + ".zip"), new File(filePath));
                        DuobeiYunClient.createTxtFlag(roomId);
                        handler.post(runnableUi);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();


//            //先解压
//            promptDialog = new PromptDialog(this);
//            promptDialog.showLoading("视频缓冲中..");
//            ZipUtil.upzipFile(filePath+"/"+roomId+".zip", filePath);
//            promptDialog.dismiss();


        } else {
            initPlayer();
        }

    }

    public void initView() {
        //竖向导航
        portraitNaviLayout = findViewById(R.id.portrait_navi_layout);
        portraitBackBtn = findViewById(R.id.portrait_back); //竖向返回按钮
        portraitBackBtn.setOnClickListener(this);
        //横向导航
        landscapeNaviLayout = findViewById(R.id.landscape_navi_layout);
        landscapeBackBtn = findViewById(R.id.landscape_back);//横向返回按钮
        landscapeBackBtn.setOnClickListener(this);
        //课程名称
        //landscapeCourseTitleText = (TextView) findViewById(R.id.landscape_course_title);//横向课程名称
        //ppt显示
        pptLayout = findViewById(R.id.pptLayout);

        //竖向播放控制
        portraitPlaybackControlLayout = findViewById(R.id.portrait_playback_control_layout);
        //竖直播放和暂停
        portraitControlBtn = findViewById(R.id.portrait_control);//竖向播放控制
        portraitControlBtn.setOnClickListener(this);
        //竖直全屏
        portraitFullScreenBtn = findViewById(R.id.portrait_fullScreen);//竖向进入全屏
        portraitFullScreenBtn.setOnClickListener(this);
        //竖直拖拽
        portraitSeekbar = findViewById(R.id.portrait_seekBar);//竖向进度
        //竖直当前时间
        portraitCurrentTimeText = findViewById(R.id.portrait_current_time);//竖向当前时间
        //竖直总时间
        portraitTotalTimeText = findViewById(R.id.portrait_total_time);//竖向总时间
        portraitPlaybackSpeedBtn = findViewById(R.id.portrait_playback_speed);//竖向回放速度控制
        portraitPlaybackSpeedBtn.setOnClickListener(this);
        //横向播放控制
        landscapePlaybackControlLayout = findViewById(R.id.landscape_playback_control_layout);
        //横向播放和暂停
        landscapeControlBtn = findViewById(R.id.landscape_control);//横向播放控制
        landscapeControlBtn.setOnClickListener(this);
        //横向当前时间
        landscapeCurrentTimeText = findViewById(R.id.landscape_current_time);//横向当前时间
        //横向退出全屏
        landscapeFullScreenBtn = findViewById(R.id.landscape_exit_fullscreen);//横向退出全屏
        landscapeFullScreenBtn.setOnClickListener(this);
        //横向倍速
        landscapePlaybackSpeedBtn = findViewById(R.id.landscape_playback_speed);//横向回放速度控制
        landscapePlaybackSpeedBtn.setOnClickListener(this);
        //横向总时间
        landscapeTotalTimeText = findViewById(R.id.landscape_total_time);//横向总时间
        //横向拖拽
        landscapeSeekbar = findViewById(R.id.landscape_seekBar);//横向进度
        //聊天区域
        chatLayout = findViewById(R.id.chat_layout);
        allMsgBtn = findViewById(R.id.allMsg);
        teacherMsgBtn = findViewById(R.id.teacherMsg);
        chatGroup = findViewById(R.id.chatGroup);

        chatList = findViewById(R.id.chatList);
        List<ChatBean> chatBeanList = new ArrayList<>();
        cusomizeaAdapter = new CusomizeaAdapter(this, R.layout.item_cusomize, chatBeanList);
        chatList.setAdapter(cusomizeaAdapter);

        teacherList = findViewById(R.id.chat_teacher_List);
        List<ChatBean> chatBeans = new ArrayList<>();
        teacherAdapter = new CusomizeaAdapter(this, R.layout.item_cusomize, chatBeans);
        teacherList.setAdapter(teacherAdapter);


        load = findViewById(R.id.load);
        mPlayerView = findViewById(R.id.player);
        view = findViewById(R.id.click_view);

        if (getOrientation(this)) {
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            int width = layoutParams.width = CommonUtils.getScreenWidth(this);
            layoutParams.height = width * 3 / 4;
            mPlayerView.setLayoutParams(layoutParams);
        }
    }


    @Override
    protected void onPause() {
        if (player != null) {
            player.pause();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.destroy();
        }

    }

    public void otherCallback() {
        chatGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == R.id.allMsg) {
                    chatList.setVisibility(View.VISIBLE);
                    teacherList.setVisibility(View.GONE);
                } else if (checkedId == R.id.teacherMsg) {
                    chatList.setVisibility(View.GONE);
                    teacherList.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void initPlayer() {
        promptDialog.dismiss();
        player = new OfflinePlaybackPlayer(this.getApplicationContext(), mPlayerView);
        player.init(Constant.DES_KEY);//des_key请向商务获取
        player.setCallback(roomId, this);//roomId；即下载资源的课程的roomId;
        //设置相应的seekbar;由于sdk中的回放界面的进度条的样式和放置位置在不同应用显示不同，所以由开发者提供；
        //进度条的进度的获取由sdk控制
        player.setSeekBar(portraitSeekbar);
        player.setSeekBar(landscapeSeekbar);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ifshow == true) {
                    hide();
                } else {
                    show();
                }
            }
        });
        player.play();
        playView();
        doupdate();
    }

    private float speed = 1.0f;

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.portrait_back) {
            if (!this.isFinishing()) {
                this.finish();
            }
        } else if (v.getId() == R.id.landscape_back) {
            changeScreen();
        } else if (v.getId() == R.id.portrait_fullScreen || v.getId() == R.id.landscape_exit_fullscreen) {
            changeScreen();
        } else if (v.getId() == R.id.portrait_playback_speed || v.getId() == R.id.landscape_playback_speed) {
            if (speed == 1f) {
                speed = 1.2f;
            } else if (speed == 1.2f) {
                speed = 1.5f;
            } else if (speed == 1.5f) {
                speed = 1.8f;
            } else if (speed == 1.8f) {
                speed = 2.0f;
            } else if (speed == 2.0f) {
                speed = 1f;
            }
            player.setPlaybackSpeed(speed);
            landscapePlaybackSpeedBtn.setText(speed + "X");
            portraitPlaybackSpeedBtn.setText(speed + "X");
        } else if (v.getId() == R.id.landscape_control || v.getId() == R.id.portrait_control) {
            if (isPlaying) {
                player.pause();
                pauseView();
            } else {
                player.play();
                playView();
            }
            isPlaying = !isPlaying;
//            }

        }

    }

    private void pauseView() {
        landscapeControlBtn.setBackgroundResource(R.drawable.play);
        portraitControlBtn.setBackgroundResource(R.drawable.play);
    }

    private void playView() {
        landscapeControlBtn.setBackgroundResource(R.drawable.stop);
        portraitControlBtn.setBackgroundResource(R.drawable.stop);
    }

    //消息列表处理
    //注：如果是本人发送；则先不走服务器，直接显示在界面上；回调即是handleContent(ChatBean chatBean)
    //handleContentList(List<ChatBean> list)是被人发送过来的消息
    //离线资源中可以只对handleContentList(List<ChatBean> list)做处理
    @Override
    public void handleContentList(final List<ChatBean> list) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (list.size() > 1) {
                    //cusomizeaAdapter.clear();
                    //teacherAdapter.clear();
                    cusomizeaAdapter.addAll(list);
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getRole() == 1) {
                            teacherAdapter.add(list.get(i));
                        }
                    }
                } else if (list.size() == 1) {
                    cusomizeaAdapter.add(list.get(0));
                    if (list.get(0).getRole() == 1) {
                        teacherAdapter.add(list.get(0));

                    }
                }
                cusomizeaAdapter.notifyDataSetChanged();
                teacherAdapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    public void handleContent(final ChatBean chatBean) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cusomizeaAdapter.add(chatBean);
                if (chatBean.getRole() == 1) {
                    teacherAdapter.add(chatBean);
                }
                cusomizeaAdapter.notifyDataSetChanged();
                teacherAdapter.notifyDataSetChanged();

            }
        });

    }

    @Override
    public void handleErrorMessage(Exception exception) {

    }

    @Override
    public void loadStart() {
        load.setVisibility(View.VISIBLE);

    }

    @Override
    public void loadFinish() {
        load.setVisibility(View.GONE);

    }

    @Override
    public void playFinish() {
        Toasty.normal(getApplicationContext(), "播放完毕").show();

    }

    @Override
    public void statusCode(int code) {

    }

    @Override
    public void exit() {

    }

    @Override
    public void currentTime(String timeStr, int progress) {
        landscapeCurrentTimeText.setText(timeStr);
        portraitCurrentTimeText.setText(timeStr);

    }

    @Override
    public void initPPT(String duration, String totalPage, String currentPage) {
        portraitTotalTimeText.setText(duration);
        landscapeTotalTimeText.setText(duration);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横向显示
            landscapeNaviLayout.setVisibility(View.VISIBLE);
            landscapePlaybackControlLayout.setVisibility(View.VISIBLE);
            //landscapeCourseTitleText.setVisibility(View.VISIBLE);
            //竖向隐藏
            portraitNaviLayout.setVisibility(View.GONE);
            portraitFullScreenBtn.setBackgroundResource(R.drawable.back);
            portraitPlaybackControlLayout.setVisibility(View.GONE);
            portraitPlaybackSpeedBtn.setVisibility(View.GONE);
            //聊天内容隐藏
            chatLayout.setVisibility(View.GONE);

            mPlayerView.setLayoutParams(layoutParams);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            //横向隐藏
            landscapeNaviLayout.setVisibility(View.GONE);
            landscapePlaybackControlLayout.setVisibility(View.GONE);
            //landscapeCourseTitleText.setVisibility(View.GONE);
            //竖向显示
            portraitNaviLayout.setVisibility(View.VISIBLE);
            portraitFullScreenBtn.setBackgroundResource(R.drawable.fullscreen);
            portraitPlaybackSpeedBtn.setVisibility(View.VISIBLE);
            portraitPlaybackControlLayout.setVisibility(View.VISIBLE);
            //聊天内容显示
            chatLayout.setVisibility(View.VISIBLE);

            int width = layoutParams.width = CommonUtils.getScreenWidth(this);
            layoutParams.height = width * 3 / 4;
            mPlayerView.setLayoutParams(layoutParams);
        }
    }

    private void hide() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //竖屏
            portraitPlaybackControlLayout.setVisibility(View.GONE);
            portraitNaviLayout.setVisibility(View.GONE);
            portraitPlaybackSpeedBtn.setVisibility(View.GONE);


        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏
            landscapeNaviLayout.setVisibility(View.GONE);
            landscapePlaybackControlLayout.setVisibility(View.GONE);
            //landscapeCourseTitleText.setVisibility(View.GONE);
        }
        ifshow = false;
    }

    private void show() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //竖屏
            portraitPlaybackControlLayout.setVisibility(View.VISIBLE);
            portraitNaviLayout.setVisibility(View.VISIBLE);
            portraitPlaybackSpeedBtn.setVisibility(View.VISIBLE);

        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏
            landscapeNaviLayout.setVisibility(View.VISIBLE);
            landscapePlaybackControlLayout.setVisibility(View.VISIBLE);
            //landscapeCourseTitleText.setVisibility(View.VISIBLE);
        }
        ifshow = true;
        doupdate();
    }

    private Boolean notfinish = false;
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOHIDE:
                    hide();
                    notfinish = false;
                    break;
            }
            super.handleMessage(msg);
        }
    };


    private void doupdate() {
        if (notfinish == true) {
            return;
        }
        notfinish = true;
        Message msg = uiHandler.obtainMessage();
        msg.what = DOHIDE;
        uiHandler.sendMessageDelayed(msg, 5000);
    }


    // 全屏显示（横屏显示）
    public void changeScreen() {
        if (getOrientation(this)) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    /**
     * 返回屏幕的方向
     *
     * @param context
     * @return true 为 portrait  false 为 landscape
     */
    public static boolean getOrientation(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    public static void startCustomizedOffinePlayBackActivity(Context context, String roomId) {
        Intent intent = new Intent(context, CustomizedOffinePlayBackActivity.class);
        intent.putExtra(ROOMID, roomId);
        context.startActivity(intent);

    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            initPlayer();
        }

    };

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    finish();
                } else {
                    changeScreen();
                }
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

}
